package com.investmenttechnologyservices.services;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.investmenttechnologyservices.model.Firm;
import com.investmenttechnologyservices.model.UserITS;
import com.investmenttechnologyservices.util.MapReduceUtils;

public class TestService {
	public Double add(String p1, String p2) throws ServletException {
		try {
			return Double.parseDouble(p1)+Double.parseDouble(p2);
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
	
	public String addFirm(String firmName, HttpServletRequest req, HttpServletResponse res) throws ServletException {
		try {
	
			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			Transaction tx = ds.beginTransaction();

			Firm myFirm = new Firm(firmName);
			ds.put(myFirm.asEntity());
			tx.commit();		

			return ("name= "+myFirm.getName());
			
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
	
	public String addUser(String firmName, HttpServletRequest req, HttpServletResponse res) throws ServletException {
		try {
			
			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
			String userId = user.getUserId().toString();
			
			Key firmKey = KeyFactory.createKey("firm", firmName);
			
			UserITS userITS = new UserITS(userId, "David Goodman", firmKey);

			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			Transaction tx = ds.beginTransaction();
			
			ds.put(userITS.asEntity());
			tx.commit();		
	
			return ("userId= "+userId);
			
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

	public String mapReduceTest1(HttpServletRequest req, HttpServletResponse res) throws ServletException {
		try {
			String ret = MapReduceUtils.sum("sales", "price", "category", 4, 4);
			return ret;
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

}
